<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Class Ads
 * @author  heyu
 */
class Ads extends MY_Controller {
    public $mAds;
    public $position;

	public function __construct(){
		parent::__construct();
        $this->loadModel('AdmAdsModel', 'mAds', 'admin');
        $this->position = getCustomConfig('ads_position');
	}
    /**
     * 首页
     */
    public function index(){
        $data = array(
            'title' => '广告管理'
        );
        $this->view('config/ads/img', $data, '');
    }

    /**
     * 广告列表
     */
    public function home(){
        $type = (int)get('type');
        if (!$type){
            show_404();
        }

        $data = array(
            'position' => $this->position[$type],
            'type' => $type,
            'title' => '广告列表'
        );
        $this->view('config/ads/home', $data, 'datatable,datepicker');
    }
	
    /**
     * 获取列表
     */
    public function getList(){
        $data = $this->mAds->adminPcGetList($this->countyItem);
        $time = strtotime(date('Y-m-d', time()));
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = '<img src="'.getImage($v['pic'],'xs').'" class="img-wh"/>';
            $data['aaData'][$k][] = $this->position[$v['ads_position']];
            $data['aaData'][$k][] = $v['ads_name'];
            if ($v['merchant_id'] > 0){
                $data['aaData'][$k][] = $v['merchant_name'];
            }else{
                $data['aaData'][$k][] = '';
            }
            $data['aaData'][$k][] = isset($v['starttime']) ? dateFormat($v['starttime']) : '';
            $data['aaData'][$k][] = isset($v['endtime']) ? dateFormat($v['endtime']) : '';
            if ($v['endtime'] + 86400 > $time){
                $status = 2;
            }else{
                $status = 1;
            }
            $data['aaData'][$k][] = $this->getStatus($status, true);
            $data['aaData'][$k][] = dateFormat($v['addtime']);
            $btnConfig = adminCreateBtn(array(
                    'label' => ' 编辑',
                    'attr' => array(
                        'href' => getUrl('config/ads/edit').'?related_id='.$v['related_id'].'&id='.$v['id'],
                        'class' => 'btn btn-xs blue-stripe default',
                    ),
                    'tag' => 'a'
                ));
            $btnConfig .= ' '.adminCreateBtn(array(
                    'label' => ' 删除',
                    'attr' => array(
                        'href' => getUrl('config/ads/delete').'?id='.$v['id'],
                        'alert-message' => "确认是否删除“ ".$v['ads_name']." ”？",
                        'class' => 'ajax-request-btn btn btn-xs red-stripe default',
                    ),
                    'tag' => 'a'
                ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 添加
     */
    public function add(){
        $this->loadModel('MerchantAdsModel', 'mMerAds', 'merchant');
        $merchant = (int)get('merchant');
        $related_id = (int)get('related_id');
        $position = $this->position;
        $title = '添加';
        if ($merchant){
            $info = $this->mMerAds->getInfo($related_id);
            $position = array(
                $info['ad_position'] => $this->position[$info['ad_position']]
            );
            $title .= ' - 商家名称：'.$info['nickname'];
            $type = $info['ad_position'];
            $day = $info['day'];
            $backUrl = getUrl('config/applyads');
        }else{
            $type = (int)get('type');
            if (!$type){
                show_404();
            }
            $backUrl = getUrl('config/ads/home?type='.$type);
            $day = 0;
        }

        $data = array(
            'day' => $day,
            'position' => $position[$type],
            'merchant' => $merchant,
            'related_id' => $related_id,
            'add' => true,
            'type' => $type,
            'title' => $title,
            'backUrl' => $backUrl,
        );
        $this->view('config/ads/from', $data, 'validation,select2,webuploader,datepicker');
    }

    /**
     * 编辑
     */
    public function edit(){
        $id = (int)get('id');
        $related_id = (int)get('related_id');
        if (!$id){
            show_404();
        }
        $title = '编辑';
        $info = $this->mAds->getInfo($id);
        if ($related_id) {
            $this->loadModel('MerchantAdsModel', 'mMerAds', 'merchant');
            $merInfo = $this->mMerAds->getInfo($related_id);

            $position = array(
                $merInfo['ad_position'] => $this->position[$merInfo['ad_position']]
            );
            $day = $merInfo['day'];
            $title .= ' - 商家名称：' . $merInfo['shop_name'];
        }else{
            $day = 0;
        }
        $data = array(
            'type' => $info['ads_position'],
            'day' => $day,
            'info' => $info,
            'position' => $position[$info['ads_position']],
            'add' => false,
            'merchant' => false,
             'related_id' => $info['related_id'],
            'title' => $title,
            'backUrl' => getUrl('config/ads/home?type='.$info['ads_position']),
        );
        $this->view('config/ads/from', $data, 'validation,select2,webuploader,datepicker');
    }

    /**
     * 保存
     */
    public function save(){
        //表单验证
        $vConf = array(
            array('ads_name', '广告名称', 'required'),
            array('ads_position', '广告位', 'required|in_list[1,2,3,4,5,6,7,8,9]'),
            array('starttime', '开始时间', 'required'),
            array('endtime', '结束时间', 'required'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        $merchant = (int)post('merchant');
        $related_id = (int)post('related_id');//商家申请记录id
        $startTime = post('starttime');
        $endTime = post('endtime');
        $adsPosition = (int)post('ads_position');
        $pic = post('pic');
        if (empty($pic)){
            $this->ajaxReturn(0, '请上传广告图片');
        }

        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime);
        if (!$startTime || !$endTime) {
            $this->ajaxReturn(0, '请选择正确的时间');
        }
        if (!$id && $startTime < strtotime(date('Y-m-d', time()))) {
            $this->ajaxReturn(0, '开始时间不得小于今天');
        }
        if ($endTime < $startTime) {
            $this->ajaxReturn(0, '结束时间不得小于开始时间');
        }
        $this->loadModel('MerchantAdsModel', 'mMerAds', 'merchant');
        if ($related_id){
            $merInfo = $this->mMerAds->getInfo($related_id);
            if (!$merInfo){
                $this->ajaxReturn(0, '申请记录不存在');
            }
            $day=floor(($endTime-$startTime)/86400)+1;
            if ($day != $merInfo['day']){
                $this->ajaxReturn(0, '开始结束时间不等于申请周期'.$merInfo['day'].'天');
            }
            $adsPosition = $merInfo['ad_position'];
        }
        if (!$id) {
            $adsConfig = array(7, 8, 9);
            if (in_array($adsPosition, $adsConfig)) {
                $p = $this->mAds->getInfoByPosition($adsPosition);
                if (!empty($p)) {
                    foreach ($p as $k => $v) {
                        if (!isset($v['endtime'])) $this->ajaxReturn(0, '该广告位已有广告');
                        if (isset($v['endtime']) && $v['endtime'] >= strtotime(date('Y-m-d', time()))) {
                            $this->ajaxReturn(0, '该广告位已有广告');
                        }
                    }
                }
            }
        }
        $data = array(
            'ads_name' => trim(post('ads_name')),
            'ads_position' => $adsPosition,
            'merchant_id' => $related_id?$merInfo['merchant_id']:0,
            'related_id' => $related_id?$related_id:0,
            'url' => post('url'),
            'starttime' => $startTime,
            'endtime' => $endTime,
        );
        $this->db->trans_begin();
        if( ! $id){
            $data['addtime'] = time();
            if( ! ($id = $this->mAds->save($data))){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
        }else{
            $info = $this->mAds->getInfo($id);
            if (!$info){
                $this->ajaxReturn(0, '广告不存在');
            }
        }
        $path = 'uploads/ads/'.$id.'/';
        $pathXs = 'uploads/ads/'.$id.'/xs/';
        $tA = explode('?', str_replace(base_url(), '', $pic));
        $img = $tA[0];
        if (!file_exists($img)) {
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '图片错误1');
        }
        $img = imageThumb($img, $path, 500, 500);
        imageThumb($img, $pathXs, 150, 150);
        if (!$img) {
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '图片错误2');
        }
        $data['pic'] = $img;
        if( ! $this->mAds->save($data, $id)){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $url = getUrl('config/ads');
        if ($related_id){
            $m = $this->mMerAds->save(array('status' => 2), $related_id);
            if (!$m){
                $this->ajaxReturn(0, '保存失败');
            }
            $url = getUrl('config/applyads');
        }
        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功', null, $url);
    }

    /**
     * 删除
     */
    public function delete(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mAds->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '广告不存在或已删除');
        }
        if ($info['merchant_id'] > 0){
            if ($info['endtime'] > strtotime(date('Y-m-d', time()))){
                $this->ajaxReturn(0, '广告投放未结束不能删除');
            }
            $tA = $this->mAds->save(array('is_delete' => 1), $id);
            if (!$tA){
                $this->ajaxReturn(0, '删除失败');
            }
        }else{
            $tA = $this->mAds->deleteAds($id);
            if (!$tA){
                $this->ajaxReturn(0, '删除失败');
            }
        }

        $this->ajaxReturn(1, '删除成功');
    }

    /**
     * 获取状态显示样式
     * @param 	integer $status
     * @param 	bool    $show
     * @return	string
     */
    protected function getStatus($status = null, $show = false){

        $config = array(1 => '已结束', 2 => '投放中');
        if( ! $status){
            return $config;
        }

        if($status && ! isset($config[$status])){
            return '';
        }

        if( ! $show){
            return $config[$status];
        }


        if($status == 1){
            return '<span class="label label-default">'.$config[$status].'</span>';
        }else if($status == 2){
            return '<span class="label label-success">'.$config[$status].'</span>';
        }

        return'';
    }
}
